﻿using BUGCOME.Infrastructure.Attribute;
using BUGCOME.Infrastructure.Extensions;
using BUGCOME.Infrastructure;
using BUGCOME.Model.Logs.Dto;
using BUGCOME.Model.Logs;
using BUGCOME.Service.Logs.IServices;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BUGCOME.ServiceCore.Services;
using BUGCOME.Infrastructure.Helper;
using BUGCOME.Repository;

namespace BUGCOME.Service.Logs
{
    /// <summary>
    /// 短信验证码记录Service业务层处理 - 提供短信验证码相关的业务操作
    /// </summary>
    [AppService(ServiceType = typeof(ISmsCodeLogService), ServiceLifetime = LifeTime.Transient)]
    public class SmsCodeLogService : BaseService<SmsCodeLog>, ISmsCodeLogService
    {
       
        /// <summary>
        /// 异步分页查询短信验证码记录列表
        /// </summary>
        /// <param name="parm">查询条件参数</param>
        /// <returns>分页后的短信验证码记录列表</returns>
        /// <exception cref="ArgumentNullException">当查询参数为空时抛出</exception>
        public async Task<PagedInfo<SmsCodeLogDto>> GetListAsync(SmscodeLogQueryDto parm)
        {
            var predicate = Expressionable.Create<SmsCodeLog>();

            predicate = predicate.AndIF(parm.Userid != null, it => it.Userid == parm.Userid);
            predicate = predicate.AndIF(parm.PhoneNum != null, it => it.PhoneNum == parm.PhoneNum);
            predicate = predicate.AndIF(parm.BeginAddTime == null, it => it.AddTime >= DateTime.Now.ToShortDateString().ParseToDateTime());
            predicate = predicate.AndIF(parm.BeginAddTime != null, it => it.AddTime >= parm.BeginAddTime);
            predicate = predicate.AndIF(parm.EndAddTime != null, it => it.AddTime <= parm.EndAddTime);
            predicate = predicate.AndIF(parm.SendType != null, it => it.SendType == parm.SendType);

            var response = await Queryable()
                .Where(predicate.ToExpression())
                .ToPageAsync<SmsCodeLog, SmsCodeLogDto>(parm);
            return response;
        }

        /// <summary>
        /// 异步获取单条短信验证码记录详情
        /// </summary>
        /// <param name="Id">记录ID</param>
        /// <returns>短信验证码记录实体</returns>
        /// <exception cref="ArgumentException">当记录ID无效时抛出</exception>
        /// <exception cref="NotFoundException">当记录不存在时抛出</exception>
        public async Task<SmsCodeLog> GetInfoAsync(long Id)
        {
            var response = await Queryable()
                .Where(x => x.Id == Id)
                .FirstAsync();

            return response;
        }

        /// <summary>
        /// 异步添加短信验证码记录
        /// </summary>
        /// <param name="model">待添加的短信验证码记录实体</param>
        /// <returns>添加成功后的短信验证码记录实体</returns>
       
        public async Task<SmsCodeLog> AddSmscodeLogAsync(SmsCodeLog model)
        {
            model.AddTime = Context.GetDate();

            var smsCode = RandomHelper.GenerateNum(6);
            var smsContent = $"验证码{smsCode},有效期10分钟。";

            var oneMinus = await Queryable().AnyAsync(f => f.PhoneNum == model.PhoneNum && SqlFunc.DateDiff(DateType.Minute, f.AddTime, model.AddTime) <= 1);
            if (oneMinus)
            {
                throw new CustomException("请稍后再试");
            }

            var oneMinusIP = await Queryable().AnyAsync(f => f.UserIP == model.UserIP && SqlFunc.DateDiff(DateType.Minute, f.AddTime, model.AddTime) <= 1);
            if (oneMinusIP)
            {
                throw new CustomException("请稍后再试");
            }

            model.SmsCode = smsCode;
            model.SmsContent = smsContent;
            model.Id = await Context.Insertable(model).ExecuteReturnSnowflakeIdAsync();
            //TODO 发送验证码

           CacheService.SetPhoneCode(model.PhoneNum.ToString(), smsCode);

            return model;
        }
    }
}
